package main

import (
    "database/sql"
    "fmt"
    "go.uber.org/zap"
    "laxkits/lib/laxmysql"
    "laxkits/lib/laxoffice"
    "strconv"
)

type QueryNames struct {
    NameMap map[string][]int64
    Sid string
}

func (qn *QueryNames)DoQuery(conn *laxmysql.LaxMySQLConn) {
    if qn.NameMap == nil {
        qn.NameMap = make(map[string][]int64)
    }
    for i := 0; i < 5; i++ {
        qsql := fmt.Sprintf("select id, name from player%d.role;", i)
        zap.S().Infof("开始查询sid[%s],player[%d], [%s]", qn.Sid, i, qsql)
        conn.Query(qsql, func(row *sql.Rows) error {
            var id int64
            var name string
            if err := row.Scan(&id, &name); err != nil {
                zap.S().Warnf("查询失败，sid[%s],player[%d]", qn.Sid, i)
                return err
            }
            if v, ok := qn.NameMap[name]; ok {
                //zap.S().Infof("遇到重名:[%s] id[%d], sid[%s]", name, id, qn.Sid)
                v = append(v, id)
                qn.NameMap[name] = v
            } else {
                idlist := make([]int64, 0)
                idlist = append(idlist, id)
                qn.NameMap[name] = idlist
            }
            return nil
        })
    }
}

func TypeQuery() {
    w, err := laxoffice.NewLaxCSVWriter("badname.csv")
    if err != nil {
        zap.S().Warn("创建csv失败", err)
        return
    }
    w.Write([]string{"sid", "name", "roleid"})
    for _, m := range xmlconfig.MysqlList {
        qname := &QueryNames{
            Sid: m.Id,
        }
        conn := laxmysql.GetLaxMySQLMgr().GetById(m.Id)
        qname.DoQuery(conn)
        for name, idlist := range qname.NameMap {
            if len(idlist) > 1 {
                for _, id := range idlist {
                    w.Write([]string{qname.Sid, name, strconv.FormatInt(id, 10)})
                }
            }
        }
    }
    w.WaitFinish()
    zap.S().Info("查询完成")
}